package bma.common.langutil.bean.packagefw;

import java.util.ArrayList;
import java.util.List;

import bma.common.langutil.bean.BeanClassBuilder;
import bma.common.langutil.bean.BeanSystem;
import bma.common.langutil.packagefw.PackageHandlerAbstract;
import bma.common.langutil.packagefw.PackageManager;

/**
 * 
 * @author guanzhong
 * @since 1.0 (imported from BMA.ESP Project)
 * 
 */
public class PackaheHandlerPojoClassBuilder extends
		PackageHandlerAbstract<List<BeanClassBuilder>> {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(PackaheHandlerPojoClassBuilder.class);

	private BeanSystem beanSystem;

	public BeanSystem getBeanSystem() {
		return beanSystem;
	}

	public void setBeanSystem(BeanSystem beanSystem) {
		this.beanSystem = beanSystem;
	}

	@Override
	protected List<BeanClassBuilder> doOpenClassLoader(PackageManager pm,
			ClassLoader loader) {
		try {
			List<Class> list = findClasses(loader, BeanClassBuilder.class);
			List<BeanClassBuilder> r = new ArrayList<BeanClassBuilder>(
					list.size());
			for (Class cls : list) {
				if (beanSystem.has(cls))
					continue;
				BeanClassBuilder c = (BeanClassBuilder) cls.newInstance();
				if (!beanSystem.add(c))
					continue;
				if (log.isDebugEnabled()) {
					log.debug("SCAN PojoClassBuilder => {}", cls.getName());
				}
				r.add(c);
			}
			return r;
		} catch (Exception e) {
			if (log.isWarnEnabled()) {
				log.warn("package scan fail", e);
			}
			return null;
		}
	}

	@Override
	protected void doCloseClassLoader(PackageManager pm, ClassLoader loader,
			List<BeanClassBuilder> item) {
		if (item != null) {
			for (BeanClassBuilder c : item) {
				beanSystem.remove(c);
			}
		}
	}

}
